package jus.aor.mobilagent.kernel;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.io.Serializable;
import java.net.URI;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Agent implements _Agent,Serializable{

	private static final long serialVersionUID = -3789916539516520489L;
		
	private Route route;

	private transient BAMLoader loader;
	
	private transient AgentServer agentServer;
	
	private String serverName;
	
	
	@Override
	public void run() {
		if(route.hasNext()){
			route.next().action.execute();
			sendMe();
		}else
			route.retour.action.execute();
	}

	private void sendMe(){
		Etape etape;
		if(route.hasNext())
			etape = route.get();
		else
			etape = route.retour;
		URI uri = etape.server;
		try {
			Socket s = new Socket(uri.getHost(), uri.getPort());
			ObjectOutputStream oop = new ObjectOutputStream(s.getOutputStream());
			oop.writeObject(loader.extractCode());
			oop.writeObject(this);
		} catch (UnknownHostException e) {
			e.printStackTrace();
			try {
				Logger logger=Logger.getLogger("jus/aor/mobilagent/"+InetAddress.getLocalHost().getHostName()+"/"+agentServer.getNameServer());
				logger.log(Level.FINE, "Agent - sendMe :", e);
			} catch (UnknownHostException ex) {};
		} catch (IOException e) {
			e.printStackTrace();
			try {
				Logger logger=Logger.getLogger("jus/aor/mobilagent/"+InetAddress.getLocalHost().getHostName()+"/"+agentServer.getNameServer());
				logger.log(Level.FINE, "Agent - sendMe :", e);
			} catch (UnknownHostException ex) {};
		}
	}
	
	@Override
	public void init(AgentServer agentServer, String serverName) {
		init((BAMLoader)this.getClass().getClassLoader(),agentServer,serverName);		
	}

	@Override
	public void init(BAMLoader loader, AgentServer server, String serverName) {
		this.loader=loader;
		
		this.agentServer=server;
		this.serverName=serverName;
	}

	@Override
	public void addEtape(Etape etape) {
		route.add(etape);
	}

	public String getServerName(){
		return serverName;
	}

	public AgentServer getAgentServer(){
		return agentServer;
	}
	
	public void setRoute(Route route){
		this.route=route;
	}
	
	public _Action retour(){
		return _Action.NIHIL;
	}
}
